package com.vg.view;

import java.util.ArrayList;

import kds.pulltorefesh.PullToRefreshBase;
import kds.pulltorefesh.PullToRefreshBase.OnLastItemVisibleListener;
import kds.pulltorefesh.PullToRefreshBase.OnRefreshListener;
import kds.pulltorefesh.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vg.com.chatonline.activity.R;
import vg.com.classdata.yahoo;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import ce51.dunghn.chatslide.LeftAndRightActivity;
import ce51.dunghn.imagethread.ExtendedImageDownloader;
import ce51.dunghn.imagethread.JsonParse;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class OtherFragmentTest extends Fragment implements
		android.widget.AdapterView.OnItemClickListener {
	ArrayList<yahoo> arr;
	ContactAdapter adapter;
	ListView lv;
	int currentPage = 1;
	int previousTotal = 0;
	boolean loading = true;
	PullToRefreshListView mPtr;
	String url = "";
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.listview_ya_test, null);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.no)
				.showImageForEmptyUri(R.drawable.no).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(6)).build();

		mPtr = (PullToRefreshListView) v.findViewById(R.id.listview);
		mPtr.setOnItemClickListener(this);

		// Set su kien khi keo xuong de load lai du lieu
		mPtr.setOnRefreshListener(new OnRefreshListener<ListView>() {
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(getActivity()
						.getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// Do work to refresh the list here.
				new RefreshContactTask().execute(1);
				currentPage = 2;
				previousTotal = 0;
				loading = false;
			}
		});

		// Add an end-of-list listener
		mPtr.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

			public void onLastItemVisible() {
			}
		});

		lv = mPtr.getRefreshableView();
		// Them textview "Load more" vao duoi listview
		View footerView = ((LayoutInflater) getActivity().getSystemService(
				Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter,
				null, false);
		lv.addFooterView(footerView);

		arr = new ArrayList<yahoo>();
		adapter = new ContactAdapter(getActivity().getApplicationContext(), arr);
		lv.setAdapter(adapter);
		lv.setOnScrollListener(new OnScrollListener() {

			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			// Keo listview de load them du lieu
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (loading) {
					if (totalItemCount > previousTotal) {
						loading = false;
						previousTotal = totalItemCount;

					}
				}
				if (!loading
						&& (totalItemCount == (firstVisibleItem + visibleItemCount))) {
					new LoadContactTask().execute(currentPage);
					currentPage++;
					loading = true;
				}
			}
		});
		return v;
	}

	public static Fragment newinstance() {
		return new OtherFragmentTest();
	}

	// Thuc hien khi them listview
	private class LoadContactTask extends
			AsyncTask<Integer, Void, ArrayList<yahoo>> {

		@Override
		protected ArrayList<yahoo> doInBackground(Integer... t) {
			ArrayList<yahoo> array = new ArrayList<yahoo>();
			array.addAll(loadContactData(t[0]));
			return array;
		}

		@Override
		protected void onPostExecute(ArrayList<yahoo> array) {
			arr.addAll(array);
			adapter.notifyDataSetChanged();
		}
	}

	// Thuc hien khi refresh listview
	private class RefreshContactTask extends
			AsyncTask<Integer, Void, ArrayList<yahoo>> {

		@Override
		protected ArrayList<yahoo> doInBackground(Integer... t) {
			ArrayList<yahoo> array = new ArrayList<yahoo>();
			array.addAll(loadContactData(t[0]));
			return array;
		}

		@Override
		protected void onPostExecute(ArrayList<yahoo> array) {
			arr.clear();
			arr.addAll(array);
			adapter.notifyDataSetChanged();

			// Call onRefreshComplete when the list has been refreshed.
			mPtr.onRefreshComplete();

			super.onPostExecute(array);
		}
	}

	// Tra ve list cho moi json data theo so trang
	public ArrayList<yahoo> loadContactData(int mPage) {
		ArrayList<yahoo> contact_list = new ArrayList<yahoo>();
		JSONArray data = new JSONArray();
		JsonParse js = new JsonParse();
		JSONObject jso = new JSONObject();
		jso = js.getJSONFromUrl("http://deduocyeu.com/json/getUserStatus.php?page="
				+ mPage + "&pagesize=10");
		try {
			data = jso.getJSONArray("data");
			for (int i = 0; i < data.length(); i++) {
				JSONObject obj = data.getJSONObject(i);
				String name_test = obj.getString("use_fullname");
				String Status_test = obj.getString("use_status");
				String img = obj.getString("use_avatar");
				yahoo yahoo = new yahoo(Status_test, name_test, img, 0);
				contact_list.add(yahoo);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return contact_list;
	}

	// Adapter cho listview
	public class ContactAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		Context c;
		ArrayList<yahoo> data = new ArrayList<yahoo>();

		public ContactAdapter(Context context, ArrayList<yahoo> d) {
			c = context;
			data = d;
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return data.get(position);
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View vi = convertView;
			if (convertView == null) {
				vi = inflater.inflate(R.layout.list_yahoo, null);
			}
			TextView txtName = (TextView) vi.findViewById(R.id.tv_name);
			TextView txtStt = (TextView) vi.findViewById(R.id.tv_status);
			ImageView imageView = (ImageView) vi.findViewById(R.id.img_yh);
			DisplayMetrics metrics = getActivity().getResources()
					.getDisplayMetrics();
			int width = metrics.widthPixels;
			int height = metrics.heightPixels;

			LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
					width / 6, width / 6);
			imageView.setLayoutParams(layout);

			txtName.setText(data.get(position).getName());
			txtStt.setText(data.get(position).getStatus());
			ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
					getActivity().getApplicationContext())
					.threadPriority(Thread.NORM_PRIORITY - 2)
					.memoryCacheSize(2 * 1024 * 1024)
					.denyCacheImageMultipleSizesInMemory()
					.discCacheFileNameGenerator(new Md5FileNameGenerator())
					.imageDownloader(
							new ExtendedImageDownloader(getActivity()
									.getApplicationContext()))
					.tasksProcessingOrder(QueueProcessingType.LIFO)
					.enableLogging().build();
			imageLoader.init(config);
			imageLoader.displayImage(data.get(position).getUrl_img(),
					imageView, options);

			return vi;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		currentPage = 1;
		previousTotal = 0;
		loading = true;
	}

	// Set su kien khi click vao item cua listview, hien thi activity chat
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		Toast.makeText(getActivity(), "ok", Toast.LENGTH_SHORT).show();
		Intent i = new Intent(getActivity(), LeftAndRightActivity.class);
		startActivity(i);
	}
}
